package com.yq.ylmall.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.ylmall.cart.mapper.CartInfoMapper;
import com.yq.ylmall.cart.service.ICartInfoService;
import com.yq.ylmall.dto.cart.CartInfoQueryDto;
import com.yq.ylmall.dto.cart.CartOrderDto;
import com.yq.ylmall.exception.ServiceException;
import com.yq.ylmall.model.cart.CartInfo;
import com.yq.ylmall.result.ResultCode;
import com.yq.ylmall.vo.cart.CartInfoPageVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CartInfoServiceImpl extends ServiceImpl<CartInfoMapper, CartInfo> implements ICartInfoService {

    private final CartInfoMapper cartInfoMapper;

    @Override
    public IPage<CartInfoPageVo> queryCartInfo(CartInfoQueryDto dto){
        IPage<CartInfoPageVo> page = new Page<CartInfoPageVo>(dto.getPageNum(), dto.getPageSize());
        return baseMapper.queryCartInfo(page, dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchRemove(CartOrderDto cartOrderDto) {
        LambdaQueryWrapper<CartInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartInfo::getUserId, cartOrderDto.getUserId());
        List<CartInfo> cartInfoList = cartInfoMapper.selectList(queryWrapper);
        try {
            if(cartInfoList.size() > 0) {
                cartInfoList.forEach(cartInfo -> {
                    if(cartOrderDto.getSkuIds().contains(cartInfo.getSkuId())) {
                        cartInfoMapper.deleteById(cartInfo.getId());
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(ResultCode.SERVICE_ERROR.getMessage());
        }
    }

    @Override
    @Transactional
    public void saveCart(List<CartInfo> cartInfos) {
        cartInfos.forEach(cartInfo -> {
            if(cartInfo.getId() == null) {
                cartInfoMapper.insert(cartInfo);
            } else {
                cartInfoMapper.updateById(cartInfo);
            }
        });
    }
}
